<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="管理方式" prop="managementType">
        <el-select v-model="queryParams.managementType" placeholder="请选择管理方式" clearable>
          <el-option
            v-for="dict in dict.type.sys_management_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="省份" prop="province">
        <el-select v-model="queryParams.province" placeholder="请选择省份" clearable @change="handleQueryProvinceChange">
          <el-option
            v-for="item in provinceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-select v-model="queryParams.city" placeholder="请选择城市" clearable @change="handleQueryCityChange">
          <el-option
            v-for="item in queryCityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="区域" prop="district">
        <el-select v-model="queryParams.district" placeholder="请选择区域" clearable>
          <el-option
            v-for="item in queryDistrictOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['house:project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['house:project:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="项目ID" align="center" prop="projectId" /> -->
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="管理方式" align="center" prop="managementType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_management_type" :value="scope.row.managementType"/>
        </template>
      </el-table-column>
      <el-table-column label="省份" align="center" prop="provinceName" />
      <el-table-column label="城市" align="center" prop="cityName" />
      <el-table-column label="区域" align="center" prop="districtName" />

      <el-table-column label="参与人员" align="center" prop="participants">
        <template slot-scope="scope">
          <el-tag
            v-for="participant in scope.row.participants"
            :key="participant"
            size="mini"
            style="margin-right: 4px; margin-bottom: 4px"
          >
            {{ getUserNickName(participant) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="客户单位" align="center" prop="customerCompany" />
      <el-table-column label="联系人" align="center" prop="customerContact" />
      <el-table-column label="联系电话" align="center" prop="customerPhone" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['house:project:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['house:project:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-house"
            @click="handleHouseList(scope.row)"
            v-hasPermi="['house:house:list']"
          >房屋列表</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管理方式" prop="managementType">
              <el-select
                v-model="form.managementType"
                multiple
                style="width: 100%"
                placeholder="请选择管理方式"
              >
                <el-option
                  v-for="dict in dict.type.sys_management_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="省份" prop="province">
              <el-select
                v-model="form.province"
                placeholder="请选择省份"
                @change="handleProvinceChange"
                style="width: 100%"
              >
                <el-option
                  v-for="item in provinceOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城市" prop="city">
              <el-select
                v-model="form.city"
                placeholder="请选择城市"
                @change="handleCityChange"
                style="width: 100%"
              >
                <el-option
                  v-for="item in cityOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="区域" prop="district">
              <el-select
                v-model="form.district"
                placeholder="请选择区域"
                style="width: 100%"
              >
                <el-option
                  v-for="item in districtOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户单位" prop="customerCompany">
              <el-input v-model="form.customerCompany" placeholder="请输入客户单位名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="customerContact">
              <el-input v-model="form.customerContact" placeholder="请输入联系人名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="customerPhone">
              <el-input v-model="form.customerPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="参与人员" prop="participants">
              <el-select
                v-model="form.participants"
                multiple
                filterable
                placeholder="请输入关键词搜索"
                style="width: 100%"
              >
                <el-option
                  v-for="item in userOptions"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProjects, getProject, delProject, addProject, updateProject } from "@/api/house/project";
import { listProvinceOptions } from "@/api/house/province";
import { listCityOptions } from "@/api/house/city";
import { listDistrictOptions } from "@/api/house/district";
import { listUser } from "@/api/system/user";

export default {
  name: "Project",
  dicts: ['sys_management_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        managementType: null,
        province: null,
        city: null,
        district: null,
        participants: [],
        customerCompany: null,
        customerContact: null,
        customerPhone: null
      },
      // 省市区数据
      provinceOptions: [],
      cityOptions: [],
      districtOptions: [],
      // 表单参数
      form: {
        projectId: null,
        projectName: null,
        managementType: null,
        province: null,
        city: null,
        district: null,
        customerCompany: null,
        customerContact: null,
        customerPhone: null,
        participants: []
      },
      // 表单校验
      rules: {
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        managementType: [
          { required: true, message: "管理方式不能为空", trigger: "change" }
        ],
        province: [
          { required: true, message: "省份不能为空", trigger: "blur" }
        ]
      },
      // 查询表单省市区数据
      queryCityOptions: [],
      queryDistrictOptions: [],
      // 添加用户选择相关数据
      userOptions: [],
      userLoading: false
    };
  },
  created() {
    this.getList();
    this.loadProvinceOptions();
    this.loadAllUsers(); // 加载所有用户
  },
  methods: {
    /** 查询项目列表 */
    getList() {
      this.loading = true;
      listProjects(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryCityOptions = [];
      this.queryDistrictOptions = [];
      this.userOptions = [];
      this.queryParams.participants = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目";
      this.form.participants = []; // 初始化参与人员字段
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const projectId = row.projectId || this.ids
      getProject(projectId).then(response => {
        this.form = response.data;
        // 设置省市区选项
        if (this.form.province) {
          this.handleProvinceChange(this.form.province);
          if (this.form.city) {
            this.handleCityChange(this.form.city);
          }
        }
        this.open = true;
        this.title = "修改项目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.projectId != null) {
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      this.$modal.confirm('是否确认删除项目编号为"' + projectIds + '"的数据项？').then(function() {
        return delProject(projectIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 跳转到房屋列表 */
    handleHouseList(row) {
      this.$router.push({
        path: '/house/house',
        query: {
          projectId: row.projectId,
          projectName: row.projectName
        }
      });
    },
    /** 加载省份数据 */
    loadProvinceOptions() {
      listProvinceOptions().then(response => {
        this.provinceOptions = response.rows.map(item => ({
          value: item.provinceCode,
          label: item.provinceName
        }));
      });
    },
    /** 加载城市数据 */
    loadCityOptions(provinceCode) {
      listCityOptions({ provinceCode: provinceCode }).then(response => {
        this.cityOptions = response.rows.map(item => ({
          value: item.cityCode,
          label: item.cityName
        }));
      });
    },
    /** 加载查询表单城市数据 */
    loadQueryCityOptions(provinceCode) {
      listCityOptions({ provinceCode: provinceCode }).then(response => {
        this.queryCityOptions = response.rows.map(item => ({
          value: item.cityCode,
          label: item.cityName
        }));
      });
    },
    /** 加载区域数据 */
    loadDistrictOptions(cityCode) {
      listDistrictOptions({ cityCode: cityCode }).then(response => {
        this.districtOptions = response.rows.map(item => ({
          value: item.districtCode,
          label: item.districtName
        }));
      });
    },
    /** 加载查询表单区域数据 */
    loadQueryDistrictOptions(cityCode) {
      listDistrictOptions({ cityCode: cityCode }).then(response => {
        this.queryDistrictOptions = response.rows.map(item => ({
          value: item.districtCode,
          label: item.districtName
        }));
      });
    },
    /** 省份选择改变事件 */
    handleProvinceChange(value) {
      if (value) {
        this.loadCityOptions(value);
        this.form.city = null;
        this.form.district = null;
        this.districtOptions = [];
      } else {
        this.cityOptions = [];
        this.districtOptions = [];
        this.form.city = null;
        this.form.district = null;
      }
    },
    /** 查询表单省份选择改变事件 */
    handleQueryProvinceChange(value) {
      if (value) {
        this.loadQueryCityOptions(value);
        this.queryParams.city = null;
        this.queryParams.district = null;
        this.queryDistrictOptions = [];
      } else {
        this.queryCityOptions = [];
        this.queryDistrictOptions = [];
        this.queryParams.city = null;
        this.queryParams.district = null;
      }
    },
    /** 城市选择改变事件 */
    handleCityChange(value) {
      if (value) {
        this.loadDistrictOptions(value);
        this.form.district = null;
      } else {
        this.districtOptions = [];
        this.form.district = null;
      }
    },
    /** 查询表单城市选择改变事件 */
    handleQueryCityChange(value) {
      if (value) {
        this.loadQueryDistrictOptions(value);
        this.queryParams.district = null;
      } else {
        this.queryDistrictOptions = [];
        this.queryParams.district = null;
      }
    },
    /** 重置省市区选项 */
    resetAreaOptions() {
      this.cityOptions = [];
      this.districtOptions = [];
    },
    // 重写reset方法
    reset() {
      this.form = {
        projectId: null,
        projectName: null,
        managementType: null,
        province: null,
        city: null,
        district: null,
        customerCompany: null,
        customerContact: null,
        customerPhone: null,
        participants: []
      };
      this.resetForm("form");
      this.resetAreaOptions();
    },
    /** 远程搜索用户 */
    remoteSearchUsers(query) {
      if (query !== '') {
        this.userLoading = true;
        listUser({
          pageNum: 1,
          pageSize: 100,
          nickName: query
        }).then(response => {
          this.userOptions = response.rows;
          this.userLoading = false;
        });
      } else {
        this.userOptions = [];
      }
    },
    /** 过滤参与人员 */
    filterParticipants(query, option) {
      return option.label.toLowerCase().includes(query.toLowerCase());
    },
    loadAllUsers() {
      listUser({
        pageNum: 1,
        pageSize: 1000
      }).then(response => {
        this.userOptions = response.rows;
      });
    },
    /** 获取用户昵称 */
    getUserNickName(userName) {
      const user = this.userOptions.find(u => u.userName === userName);
      return user ? user.nickName : userName;
    }
  }
};
</script> 